<?php namespace App\Core\Repository\Criterias\Permissions;

use App\Core\Repository\Criteria;
use App\Core\Repository\Repository;
use Auth;

class DataPermissionCritria extends Criteria{
    
    protected $field;
    protected $loginUser;
    protected $dataOperationGroupId;
    
    public function __construct($field, $dataOperationGroupId) {
        $this->field = $field;
        $this->dataOperationGroupId = $dataOperationGroupId;
        $this->loginUser = Auth::user();
    }

    public function apply(Repository $repository){
        parent::apply($repository);
        if(!$this->loginUser->isAdmin() && !$this->loginUser->isManager()){
			$this->query->whereIn($this->formatField($this->model, $this->field), $this->getDataIds());
		}
    }
    
    private function getDataIds(){
        return $this->loginUser->role ? $this->loginUser->role->getDataIdsByGroupId($this->dataOperationGroupId) : [];
    }
}